from cryptography.fernet import Fernet
import base64
import pymysql
import flask_restful

# 生成秘钥
def encKey(key):
    addkey = "干饭人,干饭魂,干饭都是人上人,干啥啥不行,干饭第一名,奥利给"
    key = str(key)+addkey
    enckey = bytes(key,encoding="utf-8")[:32]
    key_result = base64.urlsafe_b64encode(enckey)
    return key_result

def encryption(decry_data,key):
    # 获取秘钥
    keys = encKey(key)
    # 进行加密
    encli = Fernet(keys)
    enc = encli.encrypt(bytes(decry_data,encoding="utf-8"))
    # print(f"{enc}")
    return enc.decode("utf-8")

def decryption(encry_data,key):
    # 获取秘钥
    keys = encKey(key)
    # 解密
    encli = Fernet(keys)
    enkey = bytes(encry_data,encoding='utf-8')
    dec = encli.decrypt(enkey)
    return str(dec,encoding='utf-8')

def check_db_conn(host,port,username,password,dbname=None):
    try:
        pymysql.connect(host=host, port=int(port), user=username, password=password, database=dbname)
        return 1,"数据库连接成功"
    except Exception as e:
        if "Can't connect to MySQL" in str(e):
            error_info = f"数据库{host}连接超时，检查地址是否正确"
        elif "Unknown database" in str(e):
            error_info = f"数据库名{dbname}错误"
        elif "Access denied for user" in str(e):
            error_info = "用户名或密码错误"
        else:
            error_info = f"未知错误{str(e)}"
        return 0,f"检查失败【{error_info}】"

if __name__ == '__main__':
    host = "127.0.0.11"
    port = "3306"
    username = "root"
    password = "Aa123456"
    dbname = "project_info"
    rs = check_db_conn(host,port,username,password)
    print(rs)

